//
//  MyDoctorViewController.m
//  安好
//
//  Created by qinlongqing on 14/11/28.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "MyDoctorViewController.h"
#import "AppConfig.h"
#import "MyDoctorSpecifyAndFollowTableViewCell.h"
#import "AddDoctorViewController.h"
#import "DocInfoViewController.h"
#import "SpecifyDoctorManager.h"

@interface MyDoctorViewController ()<UITableViewDelegate,UITableViewDataSource,SpecifyDoctorManagerDelegate>
{
    NSArray *specifyDoctorsArray;
    NSMutableArray *followDoctorsArray;
    UITableView *mTableView;
    
    UIView *headerView1;
    UIView *headerView2;
    
    NSInteger page;
    NSInteger pageSize;
    
    UILabel *_hintLabel;
}
@end

@implementation MyDoctorViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    page = 1;
    [followDoctorsArray removeAllObjects];
    [self getFollowDoctors];

    [[SpecifyDoctorManager instance] getAllSpecifyDoctors];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    pageSize = 10;
    
    self.view.backgroundColor = UIColorFromRGB(0xf2f2f2);
    
    [self makeNavBar];
    
    [self createTableView];
    
    followDoctorsArray = [[NSMutableArray alloc]init];
    
    [SpecifyDoctorManager instance].delegate = self;
    
    _hintLabel = [[UILabel alloc] init];
    [mTableView.superview addSubview:_hintLabel];
    _hintLabel.text = @"没有更多了";
    _hintLabel.textAlignment=NSTextAlignmentCenter;
    _hintLabel.font = [UIFont systemFontOfSize:10];
    _hintLabel.textColor = [UIColor whiteColor];
    _hintLabel.backgroundColor = [UIColor blackColor];
    _hintLabel.layer.cornerRadius = 5;
    _hintLabel.layer.masksToBounds = YES;
    _hintLabel.alpha = 0;
    _hintLabel.frame = CGRectMake((mTableView.frame.size.width - 60) / 2, mTableView.frame.size.height + mTableView.frame.origin.y - 40, 60, 30);
}

-(void)makeNavBar{
    self.navigationItem.title = @"我的医生";
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backBtnclicked)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    
    // 完成
    UIBarButtonItem *addDoctorBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_添加"] style:UIBarButtonItemStylePlain target:self action:@selector(addDoctorBtnClicked)];
    addDoctorBtn.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = addDoctorBtn;
}

-(void)backBtnclicked{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)createTableView{
    mTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) style:UITableViewStylePlain];
    mTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    mTableView.backgroundColor = [UIColor clearColor];
    mTableView.delegate = self;
    mTableView.dataSource = self;
    [mTableView addFooterWithTarget:self action:@selector(getFollowDoctors)];
    [self.view addSubview:mTableView];
    
    //headerView1
    headerView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 45)];
    headerView1.backgroundColor = UIColorFromRGB(0xf2f2f2);
    //显示的字体
    NSString *specifyString = @"     指定的医生";
    UILabel *headerLabel1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, headerView1.frame.size.width, headerView1.frame.size.height - 1)];
    headerLabel1.textAlignment = NSTextAlignmentLeft;
    headerLabel1.font = [UIFont systemFontOfSize:14];
    headerLabel1.adjustsFontSizeToFitWidth = YES;
    headerLabel1.backgroundColor = [UIColor clearColor];
    NSMutableAttributedString *attributedString1 = [[NSMutableAttributedString alloc] initWithString:specifyString];
    [attributedString1 addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0x4fc1e9) range:NSMakeRange(0, specifyString.length)];
    headerLabel1.attributedText = attributedString1;
    [headerView1 addSubview:headerLabel1];
    //分割线
    UIImageView *headerImageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(0, headerView1.frame.size.height - 1, headerView1.frame.size.width, 1)];
    headerImageView1.backgroundColor = UIColorFromRGB(0xe4e4e4);
    [headerView1 addSubview:headerImageView1];
    
    //headerView2
    headerView2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 45)];
    headerView2.backgroundColor = UIColorFromRGB(0xf2f2f2);
    //显示的字体
    NSString *followString = @"     关注的医生";
    UILabel *headerLabel2 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, headerView2.frame.size.width, headerView2.frame.size.height - 1)];
    headerLabel2.textAlignment = NSTextAlignmentLeft;
    headerLabel2.font = [UIFont systemFontOfSize:14];
    headerLabel2.adjustsFontSizeToFitWidth = YES;
    headerLabel2.backgroundColor = [UIColor clearColor];
    NSMutableAttributedString *attributedString2 = [[NSMutableAttributedString alloc] initWithString:followString];
    [attributedString2 addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0x4fc1e9) range:NSMakeRange(0,followString.length)];
    headerLabel2.attributedText = attributedString2;
    [headerView2 addSubview:headerLabel2];
}

#pragma UITableViewDelegate相关
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 45;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (kScreenWidth == 414) {
        return 78;
    }
    else{
        return 65;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section== 0) {
        return specifyDoctorsArray.count;
    }
    else if (section == 1){
        return followDoctorsArray.count;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return headerView1;
    }
    else if (section == 1){
        return headerView2;
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"myDoctorSpecifyAndFollow";
    MyDoctorSpecifyAndFollowTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        if (kScreenWidth == 414) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"MyDoctorSpecifyAndFollowTableViewCell" owner:self options:nil] lastObject];
        }
        else{
            cell = [[[NSBundle mainBundle] loadNibNamed:@"MyDoctorSpecifyAndFollowTableViewCell" owner:self options:nil] firstObject];
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.doctorImageView.layer.cornerRadius = 2;
    cell.doctorImageView.layer.masksToBounds = YES;
    if (indexPath.section == 0) {//指定医生
        cell.doctorName.text = [[specifyDoctorsArray objectAtIndex:indexPath.row] valueForKey:@"doctorname"];
        [cell.doctorImageView setImageWithURL:[NSURL URLWithString:[[specifyDoctorsArray objectAtIndex:indexPath.row] valueForKey:@"avatar"]] placeholderImage:[UIImage imageNamed:@"默认头像"]];
    }
    else if (indexPath.section == 1){//关注医生
        cell.doctorName.text = [[followDoctorsArray objectAtIndex:indexPath.row] valueForKey:@"username"];
        [cell.doctorImageView setImageWithURL:[NSURL URLWithString:[[followDoctorsArray objectAtIndex:indexPath.row] valueForKey:@"avatar"]] placeholderImage:[UIImage imageNamed:@"默认头像"]];
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DocInfoViewController *docInfo = [[DocInfoViewController alloc]initWithNibName:@"DocInfoViewController" bundle:[NSBundle mainBundle]];
    if (indexPath.section == 0) {
        docInfo.doctoruid = [[specifyDoctorsArray objectAtIndex:indexPath.row] valueForKey:@"doctoruid"];
    }
    else if (indexPath.section == 1){
        docInfo.doctoruid = [[followDoctorsArray objectAtIndex:indexPath.row] valueForKey:@"doctoruid"];
    }
    [self.navigationController pushViewController:docInfo animated:YES];
}

#pragma SpecifyDoctorManagerDelegate获取所有的指定医生列表
- (void)didLoadAllSpecifyDoctors:(NSArray *)allSpecifyDoctors{
    specifyDoctorsArray = allSpecifyDoctors;
    [mTableView reloadData];
}

- (void)getFollowDoctors{//获取关注的医生
    if (page == 1) {
        [self showActionView];
    }
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"page":[NSString stringWithFormat:@"%ld",page],@"pagesize":[NSString stringWithFormat:@"%ld",pageSize]};
    [[AFHTTPRequestOperationManager manager] POST:[NSString stringWithFormat:@"%@%@",kBaseURL,kGetFollowDoctorsURL] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [mTableView footerEndRefreshing];
        
        if (page == 1) {
            [self hiddenActionView];
        }
        
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {

        }
        else{
            NSInteger numbers = followDoctorsArray.count;
            if ([[responseObject objectForKey:@"data"] count] != 0) {
                page +=1;
                [followDoctorsArray addObjectsFromArray:[responseObject objectForKey:@"data"]];
            }
            if (numbers == followDoctorsArray.count) {
                [UIView animateWithDuration:0.4f animations:^{
                    _hintLabel.alpha = 0.6;
                } completion:^(BOOL finished) {
                    if (finished) {
                        [UIView animateWithDuration:0.5 animations:^{
                            _hintLabel.alpha = 0;
                        }];
                    }
                }];
            }
            [mTableView reloadData];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [mTableView footerEndRefreshing];
        
        if (page == 1) {
            [self hiddenActionView];
        }
//        //提示信息用的view
//        MBProgressHUD *hub = [[MBProgressHUD alloc] initWithView:self.view];
//        hub.customView = [[UIView alloc]initWithFrame:CGRectZero];
//        [self.view addSubview:hub];
//        hub.mode = MBProgressHUDModeCustomView;
//        hub.labelText = @"获取关注医生数据失败!";
//        [hub show:YES];
//        [hub hide:YES afterDelay:1];
    }];
}


- (void)addDoctorBtnClicked{//添加医生
    AddDoctorViewController *addDoctor = [[AddDoctorViewController alloc]init];
    [self.navigationController pushViewController:addDoctor animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
